#! /usr/bin/env python
#
# Implement cookbook using pyfitsio
import sys
import os

import ctypes

# Use just the C-types bindings to CFITSIO
from fitsio import cfitsio, pyfitsio

def main():
    '''
    Print out all header keywords in all extensions of a FITS file.
    '''

    filename = 'atestfil.fit'
 
    status = ctypes.c_int()

    ff = pyfitsio.open(filename, mode='r')
    
    # Create string for header record
    card = ctypes.create_string_buffer('\000' * cfitsio.FLEN_CARD)

    # Attempt to move to next HDU until we get an EOF error
    ii = 1
    while True:

        try:
            hdutype = ff.move_to_hdu(ii)
        except pyfitsio.FitsIOError, e:
            print 'FITSIO error when moving to hdu, but OK'
            break

        # Get number of keywords
        nkeys = ctypes.c_int()
        keypos = ctypes.c_int()
        cfitsio.fits_get_hdrpos(ff.fptr, ctypes.byref(nkeys), 
                                ctypes.byref(keypos), ctypes.byref(status))

        print "Header listing for HDU #", ii, nkeys, keypos
        for jj in range(1, nkeys.value+1):
            cfitsio.fits_read_record(ff.fptr, jj, card, ctypes.byref(status))
            print card.value

        ii += 1

    if ff.status.value == cfitsio.END_OF_FILE:
        print 'Got EOF as expected'
    elif status.value != 0:
        pyfitsio.handle_error(status)

    ff.close()

if __name__ == '__main__':
    main()
